<?php
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Overtrue\Wechat\Shop\Product;
class ProductController extends BaseController {
	
	/**
	 * The layout that should be used for responses.
	 */
	protected $layout = 'layouts.admin';
	
	protected function setupLayout(){
		parent::setupLayout();
		$this->layout->with("nav","product");
	}
	public function showCategorys(){
		$content = View::make('admin.product.categorys');
		$this->layout->content = $content;
		//预先载入
// 		Book::with('author', 'publisher')->get();
// 		$categorys = ProductCategorys::with("children")->parents()->get();
		$categorys = ProductCategorys::treeAll();
		$content->with("categorys",$categorys);
		
		//$this->layout->with("test","123");
		//$banners = Banner::orderBy('id', 'DESC')->get();
		//$this->layout->with("title","蔓茂花廊后台管理");
		//$this->layout->content->with("banners",$banners);
	}

    public function toggleCategory(){
        $id = Input::get("id",0);
        if (empty($id)){
            return Response::json(array('success'=>false,'error'=>'没有商品分类编号'));
        }
        $category = ProductCategorys::withTrashed()->find($id);
        if ($category->trashed()){
            $category->restore();
        } else {
            $category->delete();
        }
        return Response::json(array('success'=>true));
    }
	
	public function showCategoryAdd(){
		$content = View::make('admin.product.category-add');
		$this->layout->content = $content;
		//预先载入
		// 		Book::with('author', 'publisher')->get();
		$categorys = ProductCategorys::root()->get();
		$content->with("categorys",$categorys)->with('colors',Config::get('mao.category_colors'));
	}
	
	public function postCategory(){
		$c = Input::all();
		$c["order"] = 0;
		ProductCategorys::create($c);
		return Redirect::route('product.category');
	}
	
	public function showCategoryUpdate($id){
		$content = View::make('admin.product.category-update');
		$this->layout->content = $content;
		$categorys = ProductCategorys::root()->get();
		$category = ProductCategorys::find($id);
		$content->with("categorys",$categorys)
				->with('colors',Config::get('mao.category_colors'))
				->with('category',$category);
	}
	
	public function updateCategory(){
		$c = Input::all();
		//方法一，更新发生改变的数据
// 		$category = Input::all();
// 		$category = ProductCategorys::find($c['id']);
// 		$category->fill($c);
// 		$category->save();
		//更新所有字段
// 		ProductCategorys::where('id', '=', $c['id'])->update($c);
		//ProductCategorys::save($c);
		
		//方法三，更新发生改变的数和局
		ProductCategorys::find($c['id'])->update($c);
// 		$queries = DB::getQueryLog();
// 		Log::info($queries);
		return Redirect::route('product.category');
	}
	
	public function deleteCategory(){
		$data = Input::all();
		
		//子类别
		if ($data['parentId'] > 0){
			//验证是否有产品
			$category = ProductCategorys::find($data['id']);
			$count = $category->products()->withTrashed()->count();
			if ($count > 0){
				return Response::json(array('success'=>false,'error'=>'该类别下存在产品,不能删除!'));
			} else {
				$category->forceDelete();
				return Response::json(array('success'=>true));
			}
		} else {
			//父类别
			//验证是否有子类别
			$category = ProductCategorys::find($data['id']);
			$count = $category->children()->count();
			//没有子类别
			if ($count == 0){
				$category->forceDelete();
				return Response::json(array('success'=>true));
			} else {
				//有子类别，不能删除
				return Response::json(array('success'=>false,'error'=>'存在子类别不能删除!'));
			}
		}
	}
	
	/**
	 * 显示产品列表
	 */
	public function showProducts(){
		
		//$page = Input::get('page',1);
		
		$name = Input::get("name");
		$query = Products::withTrashed();
		$search = array();
		if (!empty($name)){
			$query->where(function($subquery) use ($name){
				$subquery->where('brand', 'like', '%'.$name.'%')
				->orWhere('name',  'like', '%'.$name.'%')
				->orWhere('enname', 'like', '%'.$name.'%');
			});
			$search["name"] = $name;
		}
		$status = Input::get("status");
		if (!empty($status)){
			if ($status == 1){
				$query->whereNull("deleted_at");
			}else  if ($status == 2){
				$query->whereNotNull("deleted_at");
			}
			$search["status"] = $status;
		} else {
			$search["status"] = 0;
		}
		//paginate会自动处理分页数字
		$products = $query->orderBy('order','desc')->paginate(50);
// 		$products = Products::withTrashed()->orderBy('id','desc')->forPage(50,2)->get();
		$content = View::make('admin.product.products');
		$this->layout->content = $content;
		$content->with("products",$products);
		$content->with("search",$search);
	}
	
	public function showProductAdd(){
		
		$content = View::make('admin.product.product-add');
		$this->layout->content = $content;
		$categorys = ProductCategorys::all();
		$content->with("categorys",$categorys);
	}
	
	public function postProduct(){
// 		
		$p = Input::all();
		$id = Input::get('id',0);
		if (empty($p['discount_price'])){
			$p['discount_price'] = 0;
		}
		//
		
		$image = Input::file("image");
		if (empty($id)){
			$p['status'] = 0;
			$p['order'] = 0;
			$image = Images::storeImage($image);
			$p["image"] = $image;
			$product = Products::create($p);
			$product->order = $product->id;
			$product->save();
			$id = $product->id;
		} else {
			//如果存在则更新
			$product = Products::find($id);
			if (Input::hasFile("image")){
				$image = Images::storeImage($image,$product->image);
				$p["image"] = $image;
			} else {
				//$p["image"] = null;
				$p = array_except($p,"image");
				
			}
			//每次更新，需要重新统计商品的size,color的数量
			$sizes = ProductSizes::where("product_id","=",$id)->get();
			$colors = ProductColors::where("product_id","=",$id)->get();
			if ($sizes->count() != 0 || $colors->count() != 0){
				$count = 0;
				$sizes->each(function($size) use (&$count){
					if ($size->quantity > 0){
						$count += $size->quantity;
					}
				});
				$colors->each(function($color) use (&$count){
					if ($color->quantity > 0){
						$count += $color->quantity;
					}
				});
				
				$p["quantity"] = $count;
			}
			$product->update($p);
		}
		return Response::json(array('success'=>true,'id'=>$id));
	}
	
	public function postProductSwapSort(){
		$id1 = Input::get("id1");
		$id2 = Input::get("id2");
		$product1 = Products::withTrashed()->find($id1);
		$product2 = Products::withTrashed()->find($id2);
		DB::transaction(function() use ($product1,$product2){
			$tmp = $product1->order;
			$product1->order = $product2->order;
			$product2->order = $tmp;
			$product1->save();
			$product2->save();
		});
			return Response::json(array('success'=>true,'id1'=>$id1,'id2'=>$id2));
	}
	
	public function postProductExt(){
		$p = Input::all();
		$id = Input::get('id',0);
		if (empty($id)){
			$ext = ProductExts::create($p);
			$id = $ext->id;
		} else {
			//如果存在则更新
			ProductExts::find($id)->update($p);
		}
		return Response::json(array('success'=>true,'id'=>$id));
	}
	
	public function showProductUpdate($id){
		$content = View::make('admin.product.product-update');
		$this->layout->content = $content;
		$product = Products::fullProduct($id);
		$content->with('product',$product);
		$categorys = ProductCategorys::all();
		$content->with("categorys",$categorys);
	}
	
	public function getProduct(){
		$id = Input::get("id");
		$product = Products::fullProduct($id);
		return Response::json($product);
	}
	
	/**
	 * 添加产品图片
	 */
	public function postProductImage(){
		//$name = Config::get("mao.image_base")."foo.jpg";
		$file = Input::file('image');
		$productId = Input::get("product_id",0);
		if (empty($productId)){
			return Response::json(array('success'=>false,'error'=>'没有商品编号'));
		}
		//Image::make()->save($name);
// 		$res = Images::storeProductImage($file,$productId);
		$imageKey = Images::storeImage($file);
		//图片保存成功
		if (!empty($imageKey)){
			$image = ProductImages::create(array('image' => $imageKey,'product_id'=>$productId));
			$image->order = $image->id;
			$image->save();
			return Response::json(array(
					"id" => $image->id,
					"product_id" => $productId,
					"image" => $imageKey,
					"success" => true
			));
		}
	}
	
	/**
	 * 删除首页的大图
	 */
	public function deleteProductImage(){
		$id = Input::get("id");
// 		$productId = Input::get('product_id');
		$image = ProductImages::find($id);
		Images::delete($image->image);
		$image->delete();
		return Response::json(array('success'=>true,'id'=>$id));
	}
	
	public function postProductImageSwapSort(){
		$id1 = Input::get("id1");
		$id2 = Input::get("id2");
		$image1 = ProductImages::find($id1);
		$image2 = ProductImages::find($id2);
		DB::transaction(function() use ($image1,$image2){
			$tmp = $image1->order;
			$image1->order = $image2->order;
			$image2->order = $tmp;
			$image1->save();
			$image2->save();
		});
		return Response::json(array('success'=>true,'id1'=>$id1,'id2'=>$id2));
	}
	
	public function postProductSize(){
		$p = Input::all();
		$productId = Input::get('product_id',0);
		if (empty($productId)){
			return Response::json(array('success'=>false,'error'=>'没有商品编号'));
		}
		
		$product = Products::find($productId);
		$product->quantity += $p['quantity'];
		DB::transaction(function() use ($product,&$p){
			$product->save();
			$size = ProductSizes::create($p);
			$p['id'] = $size->id;
			$p['success'] = true;
		});
		return Response::json($p);
		
		
	}
	
	public function updateProductSize(){
		
		$data = Input::all();
		$id = Input::get("id",0);
		if (empty($id)){
			return Response::json(array('success'=>false,'error'=>'没有尺寸编号'));
		}
		$size = ProductSizes::find($id);
		
		$product = Products::find($size->product_id);
		
		$diff = $data['quantity'] - $size->quantity;
		$product->quantity = $product->quantity + $diff;
		DB::transaction(function() use ($product,$size,$data){
			$product->save();
			$size->update($data);
		});
		
		//根据主键删除
		//ProductSizes::destroy($id);
		$data['success'] = true;
		return Response::json($data);
		
		
	}
	
	public function postProductColor(){
		$p = Input::all();
		$productId = Input::get('product_id',0);
		if (empty($productId)){
			return Response::json(array('success'=>false,'error'=>'没有商品编号'));
		}
		$product = Products::find($productId);
		$product->quantity += $p['quantity'];
		DB::transaction(function() use ($product,&$p){
			$product->save();
			$color = ProductColors::create($p);
			$p['id'] = $color->id;
			$p['success'] = true;
		});
		return Response::json($p);
	}
	
	public function updateProductColor(){
		$data = Input::all();
		$id = Input::get("id",0);
		if (empty($id)){
			return Response::json(array('success'=>false,'error'=>'没有颜色编号'));
		}
		//根据主键删除
		//ProductColors::destroy($id);
		//return Response::json(array('success'=>true,'id'=>$id));
		
		$color = ProductColors::find($id);
		
		$product = Products::find($color->product_id);
		
		$diff = $data['quantity'] - $color->quantity;
		$product->quantity = $product->quantity + $diff;
		DB::transaction(function() use ($product,$color,$data){
			$product->save();
			$color->update($data);
		});
		
			//根据主键删除
			//ProductSizes::destroy($id);
		$data['success'] = true;
		return Response::json($data);
	}
	
	public function updateProductQuantity(){
		$id = Input::get("id",0);
		$product = Products::find($id);
		if (empty($product)){
			return Response::json(array('success'=>false,'error'=>'产品不存在'));
		}
		
		$productId = Input::get("productId",0);
		
// 		foreach ($sizeId1 as $i => $value) {
// 			Logger::info($value);
// 		}
// 		$sizeId2 = Input::get("sizeId");
// 		$sizeId3 = Input::get("sizeId");
// 		$sizeId4 = Input::get("0.sizeId");
		if (empty($productId)){
			DB::transaction(function() use ($product){
				$sizeIds = Input::get("sizeId");
				$sizeQuantity = Input::get("sizeQuantity");
				$colorIds = Input::get("colorId");
				$colorQuantitys = Input::get("colorQuantity");
				$quantity = 0;
				if (!empty($sizeIds)){
					foreach ($sizeIds as $i => $value) {
						$size = ProductSizes::find($value);
						$size->quantity = $sizeQuantity[$i];
						$quantity += $size->quantity;
						$size->save();
					}
				}
				
				if (!empty($colorIds)){
					foreach ($colorIds as $i => $value) {
						$color = ProductColors::find($value);
						$color->quantity = $colorQuantitys[$i];
						$quantity += $size->quantity;
						$size->save();
					}
				}
				$product->quantity = $quantity;
				$product->save();
			});
			
		} else {
			$product->quantity = Input::get("quantity",0);
			$product->save();
		}
	
// 		$color = ProductColors::find($id);
	
// 		$product = Products::find($color->product_id);
	
// 		$diff = $data['quantity'] - $color->quantity;
// 		$product->quantity = $product->quantity + $diff;
		//根据主键删除
		return Response::json(array('success'=>true,'quantity'=>$product->quantity,'id'=>$product->id));
	}
	
	public function toggleProduct(){
		$id = Input::get("id",0);
		if (empty($id)){
			return Response::json(array('success'=>false,'error'=>'没有商品编号'));
		}
		$product = Products::withTrashed()->find($id);
		if ($product->trashed()){
			$product->restore();
		} else {
			$product->delete();
		}
		return Response::json(array('success'=>true));
	}
	
	public function deleteProduct(){
		$id = Input::get("id",0);
		if (empty($id)){
			return Response::json(array('success'=>false,'error'=>'没有商品编号'));
		}
		DB::transaction(function() use ($id)
		{
// 			User::where('votes', '>', 100)->delete();
			ProductExts::where("product_id",'=',$id)->delete();
			$images = ProductImages::where("product_id",'=',$id)->get();
			$images->each(function($image){
				OSS::delete($image->image);
			});
			ProductImages::where("product_id",'=',$id)->delete();
			ProductSizes::where("product_id",'=',$id)->delete();
			ProductColors::where("product_id",'=',$id)->delete();
			//Products::destroy($id);
			$product = Products::withTrashed()->find($id);
			if (!empty($product->image)){
				OSS::delete($product->image);
			}
			$product->forceDelete($id);
		});
		//删除文件,产品的图片是根据产品编号为目录
		//Images::deleteDirectory($id);
		return Response::json(array('success'=>true));
	}
	
}